import _ from 'lodash';
import flowMap from './flowMap';
import i18n from '@src/locales'

/**
 * @description 审批设置转化成参数
 */
function formatApproveSetting(setting) {
  if(setting === undefined) return {};
  let approveSetting = _.cloneDeep(setting);
  if(approveSetting.level < 2) {
    delete approveSetting.multiApproverSetting;
  }
  if(approveSetting.level === 0) {
    approveSetting.leader = 'none';
  }
      
  // 发起人选择
  if(approveSetting.leader === 'promoter') {
    approveSetting.approvers = [];
    approveSetting.displayName = '';
    approveSetting.taskTemplateId = '';
  }
      
  // leader审批类型为表单人员
  if(approveSetting.leader && !approveSetting.leader.indexOf('formUser') > -1 && approveSetting.leader !== 'users'){
    approveSetting.approvers = [];
  }else{
    approveSetting.taskTemplateId = '';
  }
      
  // 递归:格式化多级审批
  if(Array.isArray(approveSetting.multiApproverSetting)) {
    approveSetting.multiApproverSetting = approveSetting.multiApproverSetting.map(item => formatApproveSetting(item));
  }
      
  if(typeof approveSetting.leader === 'undefined') approveSetting.leader = '';
      
  return approveSetting;
}

/** @description 将数据转化成保存需要的数据结构 */
export function convertDataToParams(config) {
  let taskTypeConfig = _.cloneDeep(config);
  let {id, flowSetting, delayBack, delayBackMin, reviewWithEvaluate, allowPause, pauseApproveSetting,
    planRemindSetting, noticeLeader, noticeUsers, cancelApproveSetting,
    autoReviewState, taskOverTimeModels } = taskTypeConfig;
  Object.keys(flowSetting).map(key => {
    if(!flowSetting[key]) flowSetting[key] = {state: false, setOut: false, overTime: 0, approvers: [], leader: "none"};
    let {state, setOut, overTime, approveSetting, reallotAppr, approveEditReceipt, questionId, transferApprove = {}, startByFaceId, finishByFaceId, finishOnlinePay = false} = flowSetting[key];
    flowSetting[key] = {
      state,
      overTime,
      ...formatApproveSetting(approveSetting),
      questionId
    }

    if(key === 'start') {
      flowSetting[key].setOut = setOut; // 出发打卡
      flowSetting[key].startByFaceId = startByFaceId
    }
    if(key === 'allot') {
      flowSetting[key].reallotAppr = reallotAppr !== 'none';

      if(transferApprove?.level === 3 ){
        transferApprove.leader = _.cloneDeep (flowSetting[key].leader)
        transferApprove.approvers = _.cloneDeep (flowSetting[key].approvers)
        transferApprove.multiApproverSetting = _.cloneDeep ( flowSetting[key].multiApproverSetting)
      }
      flowSetting[key].transferApprove = transferApprove
    }
    if(key === 'finish') {
      flowSetting[key].approveEditReceipt = approveEditReceipt
      flowSetting[key].finishByFaceId = finishByFaceId
      flowSetting[key].finishOnlinePay = finishOnlinePay
    }
    if(key === 'off') {
      flowSetting[key] = {
        ...flowSetting[key],
        ...formatApproveSetting(cancelApproveSetting),
        state: taskTypeConfig.allowCancel
      }
    }
  });
  flowSetting.pause = {
    state: allowPause,
    ...formatApproveSetting(pauseApproveSetting)
  }
  delete flowSetting.autoReview;
  //console.log(planRemindSetting,taskTypeConfig)
  let params = {
    typeId: id,
    flowSetting,
    delayBack,
    delayBackMin,
    reviewWithEvaluate,
    state: planRemindSetting.state,
    minutes: Number(planRemindSetting.minutes),
    minutesType: planRemindSetting.minutesType,
    planTimeType: planRemindSetting.planTimeType,
    planningTimeState: 'notice',
    planningTimeMes: noticeLeader ? ['none', 'leader', 'users'][Number(noticeLeader)] : 'none',
    usersIds: noticeUsers.map(item => item.userId).join(','),
    taskOverTimeModels: taskOverTimeModels.map(item => {
      let {reminders = [], overTimeState, isAhead = '0', minutes = '0', remindType, overTimeStatus} = item;
      return {
        overTimeState, 
        isAhead, 
        minutes, 
        remindType,
        overTimeStatus,
        ids: reminders.map(item => item.userId).join(','),
      };
    }),
    autoReviewState
  };
  return params;
}
/**
 * @description 记录用户操作日志参数处理
 */
export function logDataToParams(setName, taskFlowData) {
  if (JSON.stringify(taskFlowData) === '{}' || taskFlowData == null) return [];

  const FLOW_URL = i18n.t('task.setting.taskTypeSetting.flow.flowUrl'),
    OTHER_URL = i18n.t('task.setting.taskTypeSetting.flow.otherUrl'),
    CARD_URL = i18n.t('task.setting.taskTypeSetting.flow.cardUrl');

  let params = [],
    { taskTypeName, taskTypeConfig, initTaskTypeConfig, taskCardList, oldCardInfo } = _.cloneDeep(taskFlowData);

  if (setName === 'other') {//高级设置

    if (!_.isEqual(taskTypeConfig, initTaskTypeConfig)) {
      params.push(pushParams(OTHER_URL, 2, i18n.t('task.setting.taskTypeSetting.flow.editAdvancedSettings', {name: taskTypeName})));
    }

  } else if (setName === 'card') {//附加组件设置
    if (!_.isEqual(taskCardList, oldCardInfo)) {
      // 新增
      taskCardList.forEach(item => {
        if (oldCardInfo.some(v => v.id === item.id)) return;
        params.push(
          pushParams(CARD_URL, 1, i18n.t('task.setting.taskTypeSetting.flow.addSomething', {name1: taskTypeName, name2: item.name}))
        );
      });
      //删除
      oldCardInfo.forEach(item => {
        if (taskCardList.some(v => v.id === item.id)) return;
        params.push(
          pushParams(CARD_URL, 3, i18n.t('task.setting.taskTypeSetting.flow.deleteSomething', {name1: taskTypeName, name2: item.name}))
        );
      });
      //修改
      taskCardList.forEach(item => {
        oldCardInfo.forEach(el => {
          //修改使用权限和使用规则
          if (item.id === el.id) {
            //修改使用权限和使用规则
            if (!_.isEqual(item.authInfo, el.authInfo)) {
              params.push(pushParams(CARD_URL, 2, i18n.t('task.setting.taskTypeSetting.flow.editSthUseAuthority', {name1: taskTypeName, name2: item.name})));
            }

            if (!_.isEqual(item.stateCanEdit, el.stateCanEdit)
              || item.notNullFlow !== el.notNullFlow) {
              params.push(pushParams(CARD_URL, 2, i18n.t('task.setting.taskTypeSetting.flow.editSthUseRule', {name1: taskTypeName, name2: item.name})));
            }
          }
        });
      });
    }

  } else if (setName === 'flow') {//流程设置
    let curData = taskTypeConfig.flowSetting,
      initData = initTaskTypeConfig.flowSetting,
      curOverTime = taskTypeConfig.taskOverTimeModels,
      iniOvertTime = initTaskTypeConfig.taskOverTimeModels;
    for (let key in flowMap) {
      let curReallotAppr = curData[key].reallotAppr,//转排时也审批（指派工单）
        initReallotAppr = initData[key].reallotAppr,
        curApproveData = curData[key].approveSetting,
        initApproveData = initData[key].approveSetting;
      
      if (curData[key].state !== initData[key].state) {
        params.push(
          pushParams(FLOW_URL, curData[key].state ? 4 : 5, i18n.t('task.setting.taskTypeSetting.flow.openOrCloseNode', {status: curData[key].state ? i18n.t('task.setting.taskSetting.open') : i18n.t('common.base.close'), name1: taskTypeName, name2: flowMap[key].name}))
        );
      }
      
      if (curReallotAppr !== initReallotAppr || !_.isEqual(curApproveData, initApproveData)) {
        params.push(
          pushParams(FLOW_URL, 2, i18n.t('task.setting.taskTypeSetting.flow.editSthNodeApproveSetting', {name1: taskTypeName, name2: flowMap[key].name}))
        );
      }
    }

    if (!_.isEqual(curOverTime, iniOvertTime)) {//超时提醒
      curOverTime.forEach((item, index) => {

        // console.log(iniOvertTime.filter(v => v.overTimeState === item.overTimeState)[0])

        if (!_.isEqual(item,iniOvertTime[index])) {
          params.push(
            pushParams(FLOW_URL, 2, i18n.t('task.setting.taskTypeSetting.flow.editSthNodeOverTimeRemind', {name1: taskTypeName, name2: flowMap[item.overTimeState].name}))
          );
        }
        
      });
    }
  }
  // console.log('日志参数：',params);
  return params;
}
function pushParams(url, key, content) {
  return {
    operationUrl: url,
    operationType: key,
    operationContent: content
  }
}